// 全局 Ajax 设置
$.ajaxSetup({
    beforeSend: function(xhr) {
        const token = localStorage.getItem('jwt_token');
        if (token) {
            xhr.setRequestHeader('Authorization', 'Bearer ' + token);
        }
    }
});

$(document).ready(function() {
    // 如果已经登录，直接跳转到首页
    localStorage.removeItem('jwt_token');

    $('#loginForm').on('submit', function(e) {
        e.preventDefault();
        
        const loginData = {
            username: $('#username').val(),
            password: $('#password').val()
        };

        $.ajax({
            url: '/api/auth/login',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(loginData),
            success: function(response) {
                // 存储 token 和用户信息
                localStorage.setItem('jwt_token', response.token);
                localStorage.setItem('user_info', JSON.stringify({
                    id: response.id,
                    username: response.username,
                    realName: response.realName
                }));
                
                // 跳转到首页
                window.location.href = '/static/index.html';
            },
            error: function(xhr, status, error) {
                alert('登录失败: ' + (xhr.responseJSON?.error || '未知错误'));
            }
        });
    });
});
